import React, { useMemo, useState } from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import FormControlLabel from "@mui/material/FormControlLabel";
import Checkbox from "@mui/material/Checkbox";
import IconButton from "@mui/material/IconButton";
import InputAdornment from "@mui/material/InputAdornment";
import Visibility from "@mui/icons-material/Visibility";
import VisibilityOff from "@mui/icons-material/VisibilityOff";
import Link from "@mui/material/Link";
import { appState } from "@content/state/appState";
import Snackbar from "@mui/material/Snackbar";
import Alert from "@mui/material/Alert";

/** 登录组件 */
export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [remember, setRemember] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<{ email?: string; password?: string }>({});
  const [snackOpen, setSnackOpen] = useState(false);

  const isValidEmail = useMemo(() => /\S+@\S+\.\S+/.test(email), [email]);

  const validate = () => {
    const next: { email?: string; password?: string } = {};
    if (!email) next.email = "请输入邮箱";
    else if (!isValidEmail) next.email = "邮箱格式不正确";
    if (!password) next.password = "请输入密码";
    else if (password.length < 6) next.password = "密码长度不能小于 6 位";
    setErrors(next);
    return Object.keys(next).length === 0;
  };

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setLoading(true);
    // 这里可以替换为真实登录逻辑
    window.setTimeout(() => {
      setLoading(false);
      // 写入全局响应式状态（触发持久化与多上下文同步）
      appState.token = "demo-token";
      appState.profile = { email, remember, loginAt: Date.now() };
      setSnackOpen(true);
    }, 800);
  };

  return (
    <Box component="form" onSubmit={onSubmit} noValidate sx={{ display: "grid", gap: 2 }}>
      <Box>
        <Typography variant="h6" fontWeight={600} gutterBottom>
          欢迎登录
        </Typography>
        <Typography variant="body2" color="text.secondary">
          使用邮箱和密码登录你的账号
        </Typography>
      </Box>

      <TextField
        label="邮箱"
        type="email"
        size="small"
        value={email}
        error={Boolean(errors.email)}
        helperText={errors.email}
        onChange={(e) => setEmail(e.target.value)}
        autoComplete="email"
        fullWidth
      />

      <TextField
        label="密码"
        size="small"
        type={showPassword ? "text" : "password"}
        value={password}
        error={Boolean(errors.password)}
        helperText={errors.password}
        onChange={(e) => setPassword(e.target.value)}
        autoComplete="current-password"
        fullWidth
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <IconButton aria-label="toggle password visibility" onClick={() => setShowPassword((v) => !v)} edge="end">
                {showPassword ? <VisibilityOff /> : <Visibility />}
              </IconButton>
            </InputAdornment>
          ),
        }}
      />

      <Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <FormControlLabel control={<Checkbox checked={remember} onChange={(e) => setRemember(e.target.checked)} size="small" />} label={<Typography variant="body2">记住我</Typography>} />
        <Link href="#" underline="hover" variant="body2">
          忘记密码？
        </Link>
      </Box>

      <Button type="submit" variant="contained" disabled={loading} sx={{ mt: 0.5 }}>
        {loading ? "登录中..." : "登录"}
      </Button>

      <Box sx={{ textAlign: "center" }}>
        <Typography variant="body2" color="text.secondary">
          还没有账号？<Link href="#" underline="hover">立即注册</Link>
        </Typography>
      </Box>
      <Snackbar open={snackOpen} autoHideDuration={2000} onClose={() => setSnackOpen(false)} anchorOrigin={{ vertical: "top", horizontal: "center" }}>
        <Alert severity="success" variant="filled" onClose={() => setSnackOpen(false)} sx={{ width: "100%" }}>
          登录成功
        </Alert>
      </Snackbar>
    </Box>
  );
}